#coding=utf-8
#LightCam oracle监控程序
#init by hfh 20150319

import multiprocessing,subprocess
import socket,os,time,re,traceback,sys
import lc_libs
import cx_Oracle

def func(agent_hostname,dbname,sqlname,alertflag,interval,severity,schedule,holiday):
	while True:
		try:
			Node=agent_hostname
			AlertGroup="BizTrdTimeCheck"
			AlertKey=dbname+"-"+sqlname
			Summary=""
			Severity=0
			Type=0
		
			#判断时间策略
			tempflags=lc_libs.lc_schedule(schedule)
			if tempflags==False:
				time.sleep(int(interval))
				continue
			#判断节假日
			holiday_state=0
			if int(holiday)==1:
				if lc_libs.lc_isholiday():
					holiday_state=1
			if holiday_state==1:
				time.sleep(int(interval))
				continue
				
			sqlfile=open("../sql/"+sqlname+".sql",'r')
			sqlstr=sqlfile.read()
			
			dbcon=None
			try:
				dbcon=cx_Oracle.connect("cffex/biz_pass_0908@orabiz")
			except Exception:
				excinfo=traceback.format_exc()
				print excinfo
			#	AlertKey="Connect_"+dbname
			#	Summary="数据库无法连接"
			#	Severity=4
			#	Type=1
				time.sleep(120)
				continue
				
			#AlertKey="Connect_"+dbname
			#Summary="数据库连接正常"
			#Severity=4
			#Type=1
			
			cursor=dbcon.cursor()
			cursor.execute(sqlstr)
			
			if sqlname == 'checktime':
				for line in cursor.fetchall():
					res="result : %s\n" % line[0]
					print res
					logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					wfile=open('/tmp/checktime.res','w')
					wfile.write(logdate+" "+res)
					wfile.close()
					#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					#logfile.write(logdate+" "+res+"\n")
					#logfile.flush()
					if int(line[0]) > 60:
						Summary="POSILIMIT_CHECKPOINT中updatetime时间与系统相差大于60秒"
						Severity = 4
						Type=1
						strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
						print strs
						lc_libs.lc_alert(strs)
					
		except Exception:
			excinfo=traceback.format_exc()
			print excinfo
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
			time.sleep(1)
		time.sleep(int(interval))

if __name__ == "__main__":

	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	#logfile.close()
	
	agent_hostname=lc_libs.lc_gethostname()

	#主程序
	for line in open(confname):
		#if line[0] == '#' or agent_hostname != line.split("\t")[0]:
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		dbname=line.strip('\n').split("\t")[1]
		sqlname=line.strip('\n').split("\t")[2]
		alertflag=float(line.strip('\n').split("\t")[3])
		interval=line.strip('\n').split("\t")[4]
		severity=line.strip('\n').split("\t")[5]
		schedule=line.strip('\n').split("\t")[6]
		holiday=line.strip('\n').split("\t")[7]
		
#		pool = multiprocessing.Pool(processes=1)
#		result.append(pool.apply_async(func, (agent_hostname,dbname,sqlname,alertflag,interval,severity,schedule,holiday)))
		func(agent_hostname,dbname,sqlname,alertflag,interval,severity,schedule,holiday)

